<template>
    <div class='updateFile'>
        <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="视频名称" class='bord'>
                <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="视频简介" class='bord'>
                <textarea class='infoText' v-model="form.info"></textarea>
                <!-- <el-input v-model="form.info"></el-input> -->
            </el-form-item>
            <el-form-item label="视频封面" class='bord'>
                <div v-show='!videoImageBase64' class='updatePicture' @click='selectImage'>
                    <i class='el-icon-picture-outline'></i>
                </div>
                <div v-show='videoImageBase64' class='borderColor'>
                    <img :src='"data:image/png;base64,"+videoImageBase64' @click='selectImage'>
                    <div class='cover' v-show='imageRate' :style='"width:"+(100-imageRate)+"%"'></div>
                    <div v-show='imageRate' class='progressRate'>{{imageRate == 100 ? "上传完毕" : imageRate+"%"}}</div>
                </div>
                <input type='file' ref='fileImage' @change='updateImage' />
                <div class="block" v-show='videoBase64'>
                    <span class="demonstration">拉动滚动条选择视频帧数作为封面</span>
                    <el-slider :format-tooltip='formatTooltip' :max='maxduraTime' :min='0' v-model="timeValue" @change='selectImages'></el-slider>
                </div>
                <!-- <input type='button' @click='updateLoadImage' value='开始上传'> -->
            </el-form-item>
            <el-form-item label="视频上传" class='bord'>
                <div v-show='!videoBase64' class='updatePicture' @click='selectVideo'>
                    <i class='el-icon-video-camera-solid'></i>
                </div>
                <div v-show='videoBase64' class='borderColor videoLine'>
                    <div class="lineRate" :style='"margin-left:-"+(100-rate)+"%"'></div>
                    <div v-show='rate' style='color:#00f3ff;' class='progressRate'>{{rate == 100 ? "上传完毕" : rate+"%"}}</div>
                </div>
                <input type='file' ref='fileVideo' @change='updateVideo' />
                <!-- <input type='button' @click='updateLoad' value='开始上传'> -->
            </el-form-item>
            <el-form-item label="视频专题" class='bord'>
                <el-select v-model="form.value" placeholder="请选择">
                    <el-option
                    v-for="item in options"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                    </el-option>
                </el-select>
                <el-button type="primary" icon="el-icon-edit" @click='dialogVisible = true'>新增</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">立即创建</el-button>
                <el-button>取消</el-button>
            </el-form-item>
        </el-form>
        <el-dialog
            title="提示"
            :visible.sync="dialogVisible"
            width="30%"
            >
            <el-form ref="form" :model="form_topic" label-width="80px">
                <el-form-item label="专题名">
                    <el-input v-model="form_topic.name"></el-input>
                </el-form-item>
                <el-form-item label="专题类型">
                    <el-select v-model="form_topic.type" placeholder="请选择">
                        <el-option
                            v-for="item in options_topic"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit_topic">立即创建</el-button>
                    <el-button @click='dialogVisible = false'>取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <video class='hideDom' ref='video'></video>
        <canvas class='hideDom' ref='canvas'></canvas>

        <!-- 上传中全屏禁止操作层 -->
        <div class='fullCover' @click='fullCoverClick' v-show='isSave'></div>
    </div>
</template>

<script>
import { update } from './updateFile'
import { addVideo, getTopicType } from '@/api/updateFile.js'
import topicVue from "../topic/index"
import { addTopic } from '@/api/topic.js'
import { mapGetters } from 'vuex'
// import Video from '../myself/comp/video.vue'
export default {
    props: {
        saveLoad: {
            type: Function,
            default: ()=>{}
        }
    },
    components: {
        topicVue
        
    },
    comments: {
        ...mapGetters(["user"])
    },
    data() {
        return {
            dialogVisible: false,
            form: {
                name: '',
                imagebase64: '',
                videoId: '',
                imageId: '',
                info: '',
                value: ''
            },
            timeValue:0,
            maxduraTime: 100,
            isSave: false,
            rate: 0,
            imageRate: 0,
            fileName: "",
            videoBase64: "",
            fileImageName: "",
            videoImageBase64: "",
            options: [],
            form_topic: {
                type: '1',
                name: ''
            },
            options_topic: [{
                value: "1",
                label: '视频'
            },{
                value: "2",
                label: '图片'
            },{
                value: "3",
                label: '音乐'
            }],
        }
    },
    mounted (){
        this.getTopic();
    },
    methods: {

        fullCoverClick (){
            this.$message({
                type: "success",
                message: "请等待上传结束"
            })
        },

        // 显示封面选择图标
        formatTooltip (res){
            var xiaoshi = parseInt(res / 3600);
            xiaoshi != 0 ? xiaoshi += ":" : "";
            var fenzhong = parseInt(res % 3600 / 60);
            fenzhong != 0 ? fenzhong += ":" : "00:";
            var miao = parseInt(res % 3600 % 60);
            miao != 0 ? miao : "00";
            return xiaoshi + fenzhong + miao;
        },

        // 选择视频封面
        selectImage (){
            this.$refs.fileImage.click();
        },

        // 选择视频文件
        selectVideo (){
            this.$refs.fileVideo.click();
        },

        onSubmit_topic (){
            this.addTopicType();    
        },

        addTopicType (){
            this.dialogVisible = false;
            var self = this;
            addTopic({
                name: this.form_topic.name,
                type: this.form_topic.type
            }).then((e)=>{
                if( e.status == "200" ){
                    this.$message({
                        type: "success",
                        default: "类型添加成功"
                    })
                    this.getTopic(()=>{
                        this.form.value = this.options[self.options.length-1].id
                    });
                    // this.options.push({
                    //     value: this.form_topic.type,
                    //     label: this.form_topic.name
                    // })
                    // this.form.value = this.form_topic.type;
                }else{
                    this.$message({
                        type: "error",
                        default: "添加失败"
                    })
                }
            })
        },
        getTopic (fn){
            getTopicType().then((e)=>{
                this.options = e.data;
                fn && fn();
            })
        },
        onSubmit() {
            console.log('submit!');
            // if( !this.form.videoId && !this.form.imageId ){
            //     this.$message({
            //         type: "warnning",
            //         message: "请等待上传结束"
            //     })
            //     return;
            // }
            if( !this.form.name ){
                this.$message({
                    type: "warnning",
                    message: "标题不能为空哟!"
                })
                return;
            }
            if( !this.user.id ){
                this.$message({
                    type: "warnning",
                    message: "请先登录!"
                })
                return;
            }
            
            this.isSave = true;

            // 开始上传封面
            this.updateLoadImage(()=>{
                // 上传视频
                this.updateLoad(()=>{
                    // 开始提交保存
                    addVideo({
                        name: this.form.name,
                        path: this.form.videoId,
                        pathId: this.form.video_Id,
                        master: this.user.name,
                        masterId: this.user.id || 1,
                        image: this.form.imageId,
                        imageId: this.form.image_Id,
                        info: this.form.info,
                        topic : this.form.value
                    }).then((e)=>{
                        if( e.status == '200' ){
                            this.$message({
                                type: "success",
                                message: "保存成功"
                            })
                            this.$alert('视频提交完成了哟', '成功提示', {
                                confirmButtonText: '确定',
                                callback: action => {
                                    this.isSave = false;
                                }
                            });
                            this.init();
                            this.saveLoad();
                        }
                    })
                })
            });
        },
        init (){
            this.form = {
                name: '',
                imagebase64: '',
                videoId: '',
                imageId: '',
                info: '',
                value: ''
            }
            this.videoBase64 = "";
            this.videoImageBase64 = "";
            this.rate = 0;
            this.imageRate = 0;
        },
        updateImage (){
            // 上传的合计base64数据
            this.getBase64(this.$refs.fileImage.files[0]).then((res)=>{
                // 判断名称条件
                if( res.name.split(".").length > 2 ){
                    return this.$message({type: "warnning" , message: "上传文件名称不能有.*$%等特殊符号"})
                }
                this.videoImageBase64 = res.base64;
                // 获取文件名称
                this.fileImageName = res.name;
                // 开启上传
                // this.updateLoadImage();
            });;
        },
        updateVideo (event){
            // 上传的合计base64数据
            this.getBase64(this.$refs.fileVideo.files[0]).then((res)=>{
                // 判断名称条件
                if( res.name.split(".").length > 2 ){
                    return this.$message({type: "warnning" , message: "上传文件名称不能有.*$%等特殊符号"})
                }
                this.videoBase64 = res.base64;
                // 获取文件名称
                this.fileName = res.name;
                // 开启上传
                // this.updateLoad();
                // 自动获取封面
                this.selectImages()
            });
        },
        getBase64 (files){
            return new Promise((a)=>{
                // 创建文件处理对象
                var rs = new FileReader();
                // 处理完毕后事件
                rs.onload = (res)=>{
                    // 获取文件解析的base64数据
                    a({
                        base64:res.currentTarget.result.split(",")[1],
                        name: files.name
                    })
                }
                // 开始处理上传选中文件
                rs.readAsDataURL(files); 
            })
        },
        // 开始上传
        updateLoad (fn){
            // 开始上传
            var u = new update(this.fileName,this.videoBase64,0)
            // 每次完成
            u.oncomplete = (res)=>{
                this.rate = parseInt(res.rate * 100)         
                if( res.isload === true ){
                    // 如果是已经完成的状态则触发合并
                    u.mergeFile().then((res)=>{
                        this.form.videoId = res.data.path;
                        this.form.video_Id = res.id;

                        fn && fn();
                    })
                }
            };
        },
        // 开始上传封面
        updateLoadImage (fn){
            // 开始上传
            var u = new update(this.fileImageName,this.videoImageBase64,1)
            // 每次完成
            u.oncomplete = (res)=>{
                this.form.imageId = u.id;
                this.imageRate = parseInt(res.rate * 100)
                if( res.isload === true ){
                    // 如果是已经完成的状态则触发合并
                    u.mergeFile().then((res)=>{
                        this.form.imageId = res.data.path;
                        this.form.image_Id = res.id;
                        fn && fn()
                    })
                }
            };
        },

        // 选择视频的帧数来获取封面
        selectImages (){
            // 判断当前拉动的进度
            var select = this.timeValue;
            var video = this.$refs.video || document.createElement("video");
            video.setAttribute("crossOrigin",'anonymous');
            // "data:video/mp4;base64;"+
            video.src= URL.createObjectURL( this.base64ToDlob(this.videoBase64) );
            // video.style.width = "300px";
            // video.style.height = "150px";
            // video.className = "hideDom"
            // document.body.appendChild(video)
            var canvas = this.$refs.canvas || document.createElement("canvas");
            canvas.width = video.clientWidth;
            canvas.height = video.clientHeight;
            // document.body.appendChild(canvas);
            
            video.onloadeddata = ()=>{
                // 将时间节点调整为这个时间
                video.currentTime = video.duration * ( select / 100 );
                this.maxduraTime = video.duration;
                setTimeout(()=>{
                    canvas.getContext("2d").drawImage(video,0,0,canvas.width,canvas.height);
                    var dataURL = canvas.toDataURL("image/png");
                    this.videoImageBase64 = dataURL.split(",")[1];
                    // 获取文件名称
                    this.fileImageName = "asda.png";
                },1000)
                // canvas.getContext("2d").drawImage(video,0,0,canvas.width,canvas.height);
                // var dataURL = canvas.toDataURL("image/png");
                // this.videoImageBase64 = dataURL.split(",")[1];
                // // 获取文件名称
                // this.fileImageName = "asda.png";
                // 开启上传
                // this.updateLoadImage();
            }
        },

        base64ToDlob (dataurl){
            var arr = dataurl;
            var bstr = atob(arr.replace(/\s/g,''));
            var n = bstr.length;
            var u8arr = new Uint8Array(n);
            while (n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr],{ type: "video/mp4" });
        }
    }
}
</script>

<style>
    .hideDom {
        opacity: 0;
        position: fixed;
        width:300px;
        height: 150px;
        right: -300px;
        bottom:0;
    }
</style>

<style scoped>

    .bord {
        border-bottom: solid 1px #decfcf;
        padding: 15px 0;
    }

    .borderColor {
        width: 250px;
        height: 150px;
        border-radius: 4px;
        border: solid 1px #409eff;
        cursor: pointer;
        position: relative;
        animation: anim 1s;
        animation-fill-mode: forwards;
    }

    @keyframes anim {
        0% {
            opacity: 0;
            transform: translateY(-10px);
        }
        100% {
            opacity: 1;
            transform: translateY(0px);
        }
    }

    .borderColor > .cover {
        position:absolute;
        height: 100%;
        width: 100%;
        background: #000000A8;
        top: 0;
    }

    .videoLine {
        width: 95%;
        /* border-radius: 50%; */
        border: solid 1px #409eff;
        height: 75px;
        overflow: hidden;
    }

    .lineRate { 
        height: 100%;
        width: 100%;
        /* border-radius: 50%; */
        background: #66b1ff;
        margin-left: -30%;
        transition: margin 0.1s;
    }

    .borderColor > img {
        width: 100%;height:100%;
    }

    .progressRate {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-50%);
        color:#409eff;
    }

    .updateFile {
        background: #cacacaa8;
        padding: 8px;
        position:relative;
    }
    .infoText {
        width: calc(100% - 32px);
        height: calc(100% - 32px);
        padding: 15px;
        /* margin-left: 10px; */
        margin-top: 0px;
        border-radius: 4px;
        resize: none;
        border-color: #d6d6d6;
        outline-color: #3d5c77;
    }
    .updatePicture {
        border-radius: 4px;
        border:solid 1px ;
        display:flex;
        align-items: center;
        justify-content: center;
        color:#409EFF;
        width: 75px;
        height: 75px;
        cursor: pointer;
        background: #fff;
        position: relative;
        z-index: 2;
    }
    input[type='file'] {
        width: 10px;
        height: 10px;
        position: absolute;
        top: 5px;
        left: 5px;
        opacity: 0;
    }
    .fullCover {
        position: fixed;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: #3d5c7738;
        z-index: 99;
    }
</style>